import 'dart:ui';

import 'package:factoryside/api/api.dart';
import 'package:factoryside/bean/count_entity.dart';
import 'package:factoryside/bean/statistics_entity.dart';
import 'package:factoryside/bean/userinfo_entity.dart';
import 'package:factoryside/generated/json/statistics_entity_helper.dart';
import 'package:factoryside/home/page_create_order.dart';
import 'package:factoryside/provider/providers.dart';
import 'package:factoryside/utils/request_util.dart';
import 'package:factoryside/utils/utils.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'bar_chart_sample.dart';
import 'line_chart_sample.dart';
import 'page_mine.dart';

///首页

class HomePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _HomeState();
  }
}

class _HomeState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  CountEntity _countEntity=CountEntity();
  List<StatisticsEntity> statisticsList;
  UserinfoDataData userInfo;

  double top=0;

  var weekSelected=true;
  var monthSelected=false;
  var yearSelected=false;
  @override
  void initState() {
    super.initState();
    getData();
  }
  void getData() {
    context.read<User>().getUserInfo(context);
    RequestUtil.post(Api.getStatisticsOrder, {
      'UserId':Api.userName,
      'StartTime':'',
      'EndTime':'',
      'Sum':5
    }).then((value) {
      setState(() {
        List list=value['Data'];
        statisticsList=[];
        list.forEach((element) {
          statisticsList.add(statisticsEntityFromJson(StatisticsEntity(),element));
        });
      });
    });
  }
  @override
  void dispose() {
    super.dispose();
  }

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;

  RefreshController _refreshController =
  RefreshController(initialRefresh: false);

  void _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 1000));
    getData();
    _refreshController.refreshCompleted();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); //必须实现 不然 在push过后页面会刷新
    // TODO: implement build
    return Scaffold(
      body: statisticsList==null?Center(child: CircularProgressIndicator(),):SmartRefresher(
          enablePullDown: true,
          enablePullUp: false,
          controller: _refreshController,
          onRefresh: _onRefresh,
          child:CustomScrollView(
            physics: BouncingScrollPhysics(),
            slivers: <Widget>[
              SliverAppBar(
                  expandedHeight: 160.0,
                  floating: false,
                  pinned: true,
                  flexibleSpace: LayoutBuilder(
                      builder: (BuildContext context, BoxConstraints constraints) {
                        print('constraints=' + constraints.toString());
                        top = constraints.constrainHeight();
                        var height=MediaQuery.of(context).padding.top+kToolbarHeight;
                        print('height:$height');
                        return Consumer<User>(builder: (context,user,child){
                          _countEntity=user.countEntity;
                          userInfo=user.userInfo;
                          if (_countEntity!=null&&userInfo!=null) {
                            return FlexibleSpaceBar(
                                centerTitle: true,
                                title: Visibility(
                                  visible: top==height,
                                  child: Text(
                                      '${userInfo.companyName}'
                                  ),
                                ),
                                background: UserInfoHeader(userInfo: userInfo, countEntity: _countEntity));
                          }else{
                            return Container();
                          }
                        });
                      })),
              SliverList(
                delegate: SliverChildListDelegate(
                    [
//                      UserInfoHeader(userInfo: userInfo, countEntity: _countEntity),
                Container(
                  color: Colors.orange,
                    padding: EdgeInsets.all(5),
                    child: Text('最新公告：财务问题')),
                      Container(
                        padding: EdgeInsets.all(10),
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.stretch,
                          children: [
                            Row(
                              children: [
                                Expanded(child: Ink(
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: InkWell(child: Container(
                                    padding: EdgeInsets.symmetric(vertical: 20),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Image.asset('assets/servicetype2.png',width: 30,height: 30,),
                                        SizedBox(width: 10,),
                                        Text('发布安装',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),),
                                      ],
                                    ),
                                  ),onTap: (){
                                    push(context, CreateOrderPage(2));
                                  },),
                                )),
                                SizedBox(width: 10,),
                                Expanded(child: Ink(
                                  decoration: BoxDecoration(
                                      color: Colors.white,
                                      borderRadius: BorderRadius.circular(5)
                                  ),
                                  child: InkWell(child: Container(
                                    padding: EdgeInsets.symmetric(vertical: 20),
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.center,
                                      children: [
                                        Image.asset('assets/servicetype1.png',width: 30,height: 30,),
                                        SizedBox(width: 10,),
                                        Text('发布维修',style: TextStyle(fontSize: 20,fontWeight: FontWeight.bold),),
                                      ],
                                    ),
                                  ),onTap: (){
                                    push(context, CreateOrderPage(1));
                                  },),
                                )),
                              ],
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 10),
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(5)
                              ),
                              child: Column(
                                children: [
                                  Row(
                                    children: [
                                      InkWell(
                                          onTap: (){
                                            setState(() {
                                              weekSelected=true;
                                              monthSelected=false;
                                              yearSelected=false;
                                            });
                                          },
                                          child: Text('近一周',style: TextStyle(fontWeight: weekSelected?FontWeight.bold:FontWeight.normal),)),
                                      SizedBox(width: 20,),
                                      InkWell(
                                          onTap: (){
                                            setState(() {
                                              weekSelected=false;
                                              monthSelected=true;
                                              yearSelected=false;
                                            });
                                          },
                                          child: Text('近一月',style: TextStyle(fontWeight: monthSelected?FontWeight.bold:FontWeight.normal),)),
                                      SizedBox(width: 20,),
                                      InkWell(
                                          onTap: (){
                                            setState(() {
                                              weekSelected=false;
                                              monthSelected=false;
                                              yearSelected=true;
                                            });
                                          },
                                          child: Text('近一年',style: TextStyle(fontWeight: yearSelected?FontWeight.bold:FontWeight.normal),)),
                                    ],
                                  ),
                                  SizedBox(height: 10,),
                                  LineChartSample1(),
                                ],
                              ),
                            ),
                            Container(
                              margin: EdgeInsets.fromLTRB(0,10,0,70),
                              padding: EdgeInsets.all(10),
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.circular(5)
                              ),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
//                                  Text('发单区域统计'),
//                                  SizedBox(height: 10,),
                                  BarChartSample1(statisticsList),
                                ],
                              ),
                            ),
                          ],
                        ),
                      )
                    ]
                ),
              ),
            ],
          )
      ),
      floatingActionButton: FloatingActionButton(
        heroTag: null,
        onPressed: () async {
          push(context, CreateOrderPage(2));
          // ignore: deprecated_member_use
//          Scaffold.of(context).showSnackBar(
//            SnackBar(content: Text('Favorited')),
//          );
        },
        child: const Icon(Icons.add),
      ),
    );
  }
}
